import requests


# 获取数据
def get_page(url):
    try:
        r = requests.get(url)
        if r.status_code == 200:
            return r.json()
    except requests.ConnectionError as e:
        print(e)


# 解析数据
def parser_page(json):
    if json:
        items = json.get("data")
        for i in range(len(items)):
            item = items[i]
            qsrank = {}
            if "=" in item["rank_display"]:
                rk_str = str(item["rank_display"]).split("=")[-1]
                qsrank["rank_display"] = rk_str
            else:
                qsrank["rank_display"] = item["rank_display"]
            qsrank["title"] = item["title"]
            qsrank["region"] = item["region"]
            qsrank["score"] = item["score"]
            # url可根据需求提取
            qsrank["url"] = item["url"]
            yield qsrank


# 主函数
def main():
    url = 'https://www.qschina.cn/sites/default/files/qs-rankings-data/cn/2208747_indicators.txt'
    path = "./1.txt"
    
    json = get_page(url)
    results = parser_page(json)

    for result in results:
        with open(path, "a") as f:  # path 是文件要存储的地方
            f.write(
                "{:10}{:50}{:^88}{:>}\n".format(
                    result["rank_display"],
                    result["title"],
                    result["region"],
                    result["score"],
                )
            )
            f.close()